// pages/ordersDetail/myOrders.js

var apiHost = wx.getStorageSync('apiHost');
var yunId = "";
var orderNo = "";
var openId = "";
var detailList = "";
var goodOrders = new Array();
var acceptTime = "";
var deliveryTimeType = "";
var payLimitTime = "";
var isSelfClaim = "";
var flag = "";
var phone = "";
var state = "";
var orderstate = "";
var cOrderNo = "";
var leftTime = "";
var types = "";
var list = new Array();
var limitTime = "";
var deliveryFee = 0;
var json = "";
var createTime = "";
var orderCretime = "";
var paytype = "";
var onemoreFlag = false;
var deliveryLimitTime = "";
var sendleftTime = "";
var paylefttime = "";
var actualPay = "";
var reciveName = "";
var recivePhone = "";
var areaId = "";
var reciveAddress = "";
var goodOrders = "";
var deliveryTimeType = "";
var deliveryTimeId = "";
var alertMsg = new Array();
var util = require('../../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hiddenLoading: true,    //loading
    showModal: false,
    hiddenLoading: true,    //loading
    state: state
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    var that = this;
    //显示加载动画
    this.setData({
      hiddenLoading: false
    });
    // console.log(options);
    yunId = options.yunId,
      openId = options.openId,
      orderNo = options.orderNo,
      flag = options.flag

    that.orderDetail();

    that.setData({
      yunId: yunId,
      openId: openId,
      goodOrders: goodOrders
    })
    /**
        * 获取系统信息
        */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
    // that.orderDetail();
  },
  call: function (event) {
    var phone = event.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  },
  delOrder: function (openId) {
    var that = this;
    that.setData({
      showModal: true
    })
  },
  onemore: function (e) {
    var that = this;
    onemoreFlag = true;
    goodOrders = new Array();
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    //获取订单列表，拼接商品信息
    wx.request({
      url: apiHost + 'xcx/order/detail',
      data: {
        yunId: yunId,
        openId: openId,
        orderNo: orderNo
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        for (var i = 0; i < res.data.data.goods.length; i++) {
          var good = {
            spuId: res.data.data.goods[i].spuId,
            count: res.data.data.goods[i].count
          }
          goodOrders.push(good);
        }
        deliveryFee = res.data.data.deliveryFee;
        createTime = util.formatTime(new Date()).toString();
        json = JSON.stringify(goodOrders);
        wx.navigateTo({
          url: '/pages/userOrder/confirm/confirm?yunId=' + yunId + "&openId=" + openId + "&goodOrders=" + json + "&createTime=" + createTime,
        })

        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
      }
    })

  },
  cancel: function () {
    this.setData({
      showModal: false
    })
  },
  confirm: function (event) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    wx.request({
      url: apiHost + 'xcx/order/del',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        this.setData({
          showModal: false
        })
        if (res.data.code == "10000") {
          /**
                  * 获取系统信息
                  */
          wx.getSystemInfo({
            success: function (res) {
              that.setData({
                hiddenLoading: true
              });
            }
          });

          wx.showToast({
            title: '删除成功!',
            icon: 'success',
            duration: 2000
          })
          /**
        * 获取系统信息
        */
          wx.getSystemInfo({
            success: function (res) {
              that.setData({
                hiddenLoading: true
              });
            }
          });
          // 跳转订单列表
          wx.navigateTo({
            url: '/pages/order/order',
            data: {
              yunId: yunId,
              openId: openId
            }
          })
        }
      }
    })
  },
  refuse: function (openId) {
    var that = this;
    var state = 0;
    wx.request({
      url: apiHost + 'xcx/order/confirmAcceptOrder',
      data: {
        yunId: yunId,
        state: state,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        
        if (res.data.code == "10000") {
          // that.orderDetail();
        }
      },
    })
  },
  accept: function (e) {
    var state = 1;
    var that = this;
    wx.request({
      url: apiHost + 'xcx/order/confirmAcceptOrder',
      data: {
        yunId: yunId,
        state: state,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        if (res.data.code == "10000") {
          // that.orderDetail();
        }
      },
    })
  },
  pay: function () {
    var payTyime = util.formatTime(new Date()).toString();
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    // console.log("%%%%%%%%")
    // console.log(orderNo, openId, yunId)
    wx.request({
      url: apiHost + 'xcx/order/notPaySubmit',
      data: {
        openId: openId,
        yunId: yunId,
        orderNo: orderNo
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (result) {
        // console.log("!!!!");
        // console.log(result)
        /**
       * 获取系统信息
       */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
        // console.log(result)
        if (result.data.code == "10000") {
          var timeStamp = result.data.data.timeStamp
          var nonceStr = result.data.data.nonceStr
          var packages = result.data.data.package
          var paySign = result.data.data.paySign
          var signType = result.data.data.signType
          var appId = result.data.data.appId
          orderNo = result.data.data.orderNo;
          //调支付接口
          wx.requestPayment({
            appId: appId,
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            'package': packages,
            signType: signType,
            paySign: paySign,
            'success': function (res) {
              console.log(res);
              //下单成功后跳转到订单详情页
              wx.navigateTo({
                url: '/pages/userOrder/orderDetail/orderDetail?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId + "&flag=" + flags,
              })
            },
            'fail': function (res) {
            }
          })
        } else {
          alertMsg.push(res.data.msg);
          that.setData({
            alertModel: true,
            alertMsg: alertMsg
          })
        }
        if (result.data.code == "10098") {
          alertMsg.push("商品库存不足！");
          that.setData({
            alertModel: true
          })
        }
        that.setData({
          alertMsg: alertMsg
        })
      }
    })
  },
  
  //评价
  judge: function (e) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    orderNo = e.currentTarget.dataset.reforderno;
    wx.navigateTo({
      url: '/pages/userOrder/judge/judge?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId,
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  cancel: function (event) {
    this.setData({
      showModal: false,
      showConfirmArea: false,
      showCancelArea: false
    })
  },
  confirm: function (event) {
    var that = this;
    wx.request({
      url: apiHost + 'xcx/order/del',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        that.setData({
          showModal: false
        })
        if (res.data.code == "10000") {
          wx.showToast({
            title: '删除成功!',
            icon: 'success',
            duration: 2000
          })
          // 跳转订单列表
          wx.navigateTo({
            url: '/pages/userOrder/userOrderList/userOrderList',
            data: {
              yunId: yunId,
              openId: openId
            }
          })
        }
      }
    })
  },
  confirmOrders: function (e) {
    cOrderNo = e.currentTarget.dataset.reforderno
    this.setData({
      showConfirmArea: true,
      cOrderNo: cOrderNo
    })
  },
  cancelOrder: function (e) {
    orderNo = e.currentTarget.dataset.reforderno;
    this.setData({
      showCancelArea: true,
      cancelNo: orderNo
    })
  },
  cancelO: function () {
    var that = this;
    that.setData({
      alertModel: false
    })
  },
  confirmCancel: function (e) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });

    orderNo = e.currentTarget.dataset.cancelorderNo;
    wx.request({
      url: apiHost + 'xcx/order/cancel',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId,
        'type': '1'
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
        if (res.data.code == "10000") {
          wx.showToast({
            title: '取消订单成功!',
            icon: 'success',
            duration: 2000
          })
          that.orderDetail();
        } else {
          alertMsg.push(res.data.msg);
          that.setData({
            alertModel: true,
            alertMsg: alertMsg
          })
        }
      }
    })
    that.setData({
      showCancelArea: false
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  confirmOrder: function (e) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    orderNo = e.currentTarget.dataset.orderNo;
    wx.request({
      url: apiHost + 'xcx/order/confirmReceipt',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        if (res.data.code == "10000") {
          wx.showToast({
            title: '确认收货成功!',
            icon: 'success',
            duration: 2000
          })
          that.orderDetail();
        }
      }
    })
    this.setData({
      showConfirmArea: false
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },

  //订单详情
  orderDetail: function (openId) {
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + 'xcx/order/detail',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        console.log("orderdetail is ")
        console.log(res);
        var leftTime = null;
        wx.hideLoading();   //隐藏加载loading
        acceptTime = res.data.data.acceptTime;
        orderCretime = res.data.data.createTime;
        payLimitTime = res.data.data.payLimitTime;
        state = res.data.data.state;
        orderstate = res.data.data.state;
        orderNo = res.data.data.orderNo
        phone = res.data.data.phone;
        list = res.data.data;
        console.log(list);
        limitTime = res.data.data.limitTime
        deliveryLimitTime = res.data.data.deliveryLimitTime
        paytype = res.data.data.payType


        if (paytype == "0") {
          paytype = "货到付款"
        }
        if (paytype == "1") {
          paytype = "微信支付"
        }
        that.setData({
          detailList: res.data.data,
          state: state,
          phone: phone,
          orderNo: orderNo,
          limitTime: limitTime,
          paytype: paytype
        })

        //获取底部按钮区域
        var queryc = wx.createSelectorQuery();

        var sunbmitCon = "";
        deliveryTimeType = "";
        isSelfClaim = "";
        //计算评价列表高度
        queryc.select('#sunbmitCon').boundingClientRect()
        queryc.exec(function (res) {
          sunbmitCon = res[0].height;
          /** 
           * 获取系统信息 
           */
          wx.getSystemInfo({
            success: function (res) {
              that.setData({
                winWidth: res.windowWidth,
                winHeight: res.windowHeight - sunbmitCon,
                hiddenLoading: true
              });
            }
          });
        });
      },
    })
  },
  contact: function (event) {
    var phone = event.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  },
  // 页面渲染完成后 调用  
  onReady: function () {
    var intervals = setInterval(function () {
      var that = this;
      leftTime = "";
      var nowTime = util.formatTime(new Date()).toString();
      var Nhour = nowTime.substring(11, 13) * 1;
      var Nmin = nowTime.substring(14, 16) * 1;
      var Nsec = nowTime.substring(17, 19) * 1;
      types = "2";
      // console.log(list);
      // for (var i = 0; i < list.length; i++) {
      if (list.state == "1") {
        var payTime = list.payTime;
        orderNo = list.orderNo;
        var createtime = list.createTime;
        if (list.payType == "0") {
          var Emin = createtime.substring(14, 16) * 1 + limitTime * 1;
          var Ehour = createtime.substring(11, 13) * 1;
          var Esec = createtime.substring(17, 19) * 1;
        } else {
          var Emin = payTime.substring(14, 16) * 1 + limitTime * 1;
          var Ehour = payTime.substring(11, 13) * 1;
          var Esec = payTime.substring(17, 19) * 1;
        }
        
        if (Emin > 60) {
          Emin = Emin - 60;
          Ehour = Ehour + 1;
        }
        var Lmin = 0;
        var Lsec = 0;
        var Lhour = 0;
        if (Esec >= Nsec) {
          Lsec = Esec - Nsec;
        } else {
          Esec = Esec + 60;
          Lsec = Esec - Nsec;
          Emin = Emin - 1;
        }
        if (Emin >= Nmin) {
          Lmin = Emin - Nmin;
        } else {
          Emin = Emin + 60;
          Lmin = Emin - Nmin;
          Ehour = Ehour - 1;
        }
        Lhour = Ehour - Nhour;
        //当前时间是否大于过期时间判断
        var flags = false;
        if (Nhour > Ehour) {
          flags = true;
          // console.log("11111$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        }else{
          flags = false;
        }
        if (Nhour == Ehour) {
          // console.log("######");
          if (Nmin > Emin) {
            flags = true;
            // console.log("2222$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
          } else {
            flags = false;
          }
          if (Nmin == Emin) {
            if (Nsec > Esec) {
              flags = true;
              // console.log("3333$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
            } else {
              flags = false;
            }
          }
        }
        // console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        // console.log(flags);
        if ((Lmin == 0 && Lsec == 0) || flags) {
          console.log("5555");
          wx.request({
            url: apiHost + 'xcx/order/confirmAcceptOrder',
            data: {
              yunId: yunId,
              openId: openId,
              orderNo: orderNo,
              orderNo: orderNo,
              state: '0',
              'type': types
            },
            header: {
              'conttent-type': 'application-json'
            },
            success: function (res) {
              that.orderDetail();
            }
          })
        }
        if (Lmin < limitTime * 1) {
          leftTime = Lmin + "分" + Lsec + "秒";
        }

      }

      that.setData({
        leftTime: leftTime
      })

      //待付款倒计时
      //待付款倒计时
      // console.log("paying ！！！！！~~~~~")
      // console.log(list)
      if (list.state == "0") {
        // console.log("paying ~~~~~")
        var that = this;
        var nowTime = util.formatTime(new Date()).toString();
        var Emin = orderCretime.substring(14, 16) * 1;
        var Ehour = orderCretime.substring(11, 13) * 1 + payLimitTime * 1;
        var Esec = orderCretime.substring(17, 19) * 1;

        var NHour = nowTime.substring(11, 13) * 1;
        var Nmin = nowTime.substring(14, 16) * 1;
        var Nsec = nowTime.substring(17, 19) * 1;
        var LSec = 0;
        var LMin = 0;
        var LHour = 0;

        if (Esec >= Nsec) {
          LSec = Esec - Nsec;
        } else {
          Esec = Esec + 60;
          LSec = Esec - Nsec;
          Emin = Emin - 1;
        }
        if (Emin >= Nmin) {
          LMin = Emin - Nmin;
        } else {
          Emin = Emin + 60
          LMin = Emin - Nmin;
          Ehour = Ehour - 1;
        }
        // console.log("666666")
        // console.log(Ehour, NHour)
        if (Ehour >= NHour) {
          LHour = Ehour - NHour;
          if (LHour <= deliveryLimitTime * 1) {
            paylefttime = LHour + "时" + LMin + "分" + LSec + "秒";
            that.setData({
              paylefttime: paylefttime
            })
          }
        }
        else {
          paylefttime = "";
          that.setData({
            paylefttime: paylefttime
          })
        }
      }
    }.bind(this), 1000);

    //自动收货倒计时
    if (typeof (acceptTime) != "undefined") {
      var interval = setInterval(function () {
        var that = this;
        var nowTime = util.formatTime(new Date()).toString();

        var Emin = acceptTime.substring(14, 16) * 1;
        var Ehour = acceptTime.substring(11, 13) * 1 + deliveryLimitTime * 1;
        var Esec = acceptTime.substring(17, 19) * 1;

        var NHour = nowTime.substring(11, 13) * 1;
        var Nmin = nowTime.substring(14, 16) * 1;
        var Nsec = nowTime.substring(17, 19) * 1;
        var LSec = 0;
        var LMin = 0;
        var LHour = 0;

        if (Esec >= Nsec) {
          LSec = Esec - Nsec;
        } else {
          Esec = Esec + 60;
          LSec = Esec - Nsec;
          Emin = Emin - 1;
        }
        if (Emin >= Nmin) {
          LMin = Emin - Nmin;
        } else {
          Emin = Emin + 60
          LMin = Emin - Nmin;
          Ehour = Ehour - 1;
        }
        if (Ehour >= NHour) {
          LHour = Ehour - NHour;
          if (LHour <= deliveryLimitTime * 1) {
            sendleftTime = LHour + "时" + LMin + "分" + LSec + "秒";
            that.setData({
              sendleftTime: sendleftTime
            })
          }
        } else {
          sendleftTime = "您的订单将在12小时内将";
          that.setData({
            sendleftTime: sendleftTime
          })
        }
      }.bind(this), 1000);
    }

    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var flags = "tabBar";
    if (flag == "list") {
      wx.navigateTo({
        url: '/pages/userOrder/userOrderList/userOrderList?flag=' + flags
      })
    }
    if (flag == "index") {
      wx.switchTab({
        url: '/pages/index/index'
      })
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
  },
})
